package com.longcai.cm.utils;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

import static java.lang.Math.*;

public class GeoCalculator {

    // 地球半径，单位为公里
    private static final int EARTH_RADIUS = 6371;

    public static int calculateDistance(double lat1, double lon1, double lat2, double lon2) {
        double latDistance = toRadians(lat2 - lat1);
        double lonDistance = toRadians(lon2 - lon1);
        double a = sin(latDistance / 2) * sin(latDistance / 2) +
                cos(toRadians(lat1)) * cos(toRadians(lat2)) *
                        sin(lonDistance / 2) * sin(lonDistance / 2);
        double c = 2 * atan2(sqrt(a), sqrt(1 - a));
        return (int) (EARTH_RADIUS * c * 1000);
    }

    public static double toRadians(double degree) {
        return degree * (Math.PI / 180);
    }

    public static void main(String[] args) {
        double lat1 = 40.7128;
        double lon1 = -74.0060;
        double lat2 = 40.7829;
        double lon2 = -73.9654;

        double distance = calculateDistance(lat1, lon1, lat2, lon2);
        System.out.println("Distance (km): " + distance);
    }
}
